﻿import 'package:getx_scaffold/getx_scaffold.dart';
import 'diet_statistics_state.dart';
import '../../../../core/repository/default_api.dart';
import '../../../../entity/food_statistics.dart';
import '../../../../services/device_sn_manager.dart';

/// 饮食统计控制器
class DietStatisticsLogic extends GetxController {
  final DietStatisticsState state = DietStatisticsState();

  @override
  void onInit() {
    super.onInit();
    _updateDateText();
    _loadFoodRecords();
  }

  /// 获取设备序列号
  String _getDeviceSn() {
    try {
      final deviceSnManager = Get.find<DeviceSnManager>();
      return deviceSnManager.getDeviceSn();
    } catch (e) {
      print('⚠️ 无法获取DeviceSnManager: $e');
      return '';
    }
  }

  /// 加载饮食记录
  Future<void> _loadFoodRecords() async {
    try {
      state.isLoading.value = true;

      // 获取设备SN
      final deviceSn = _getDeviceSn();

      // 获取当前日期（总是传今天）
      final now = DateTime.now();
      final recordDate = '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')}';
      String type = '';

      // 根据选中的时间段设置参数
      switch (state.selectedPeriod.value) {
        case 0: // 日
          type = '1';
          break;
        case 1: // 周
          type = '2';
          break;
        case 2: // 月
          type = '3';
          break;
      }

      // 调用接口（recordDate 总是传今天）
      final dynamic apiData = await DefaultApi().queryFoodListGet<dynamic>(
        deviceSn: deviceSn,
        recordDate: recordDate,
        type: type,
      );

      if (apiData != null &&
          apiData['code'] == 200 &&
          apiData['data'] != null) {
        final statistics =
            FoodStatistics.fromMap(apiData['data'] as Map<String, dynamic>);
        state.foodStatistics.value = statistics;
      } else {
        state.foodStatistics.value = null;
      }
    } catch (e) {
      print('❌ 加载饮食记录失败: $e');
      state.foodStatistics.value = null;
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 切换时间段（日/周/月）
  void changePeriod(int index) {
    state.selectedPeriod.value = index;
    _updateDateText();
    _loadFoodRecords();
  }

  /// 更新日期文本
  void _updateDateText() {
    final now = DateTime.now();
    switch (state.selectedPeriod.value) {
      case 0: // 日
        state.currentDateText.value =
            '${now.year}年${now.month.toString().padLeft(2, '0')}月${now.day.toString().padLeft(2, '0')}日，星期${_getWeekday(now.weekday)}';
        break;
      case 1: // 周
        state.currentDateText.value = '本周';
        break;
      case 2: // 月
        state.currentDateText.value = '${now.year}年${now.month}月';
        break;
    }
  }

  /// 获取星期几
  String _getWeekday(int weekday) {
    const weekdays = ['一', '二', '三', '四', '五', '六', '日'];
    return weekdays[weekday - 1];
  }
}
